import redis.asyncio as redis
from contextlib import asynccontextmanager
from fastapi import FastAPI

from fastapi_limiter import FastAPILimiter

from config import REDIS_HOST,REDIS_PASSWORD,REDIS_PORT

REDIS_USERNAME = ""
REDIS_DB = 7  # redis消息队列所在db，请不要在这个db放太多其他键值对，框架里面有的功能会scan扫描unacked的键名，使用单独的db。

REDIS_URL = f"redis://{REDIS_USERNAME}:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"

@asynccontextmanager
async def lifespan(_: FastAPI):
    redis_connection = redis.from_url(REDIS_URL, encoding="utf8")
    await FastAPILimiter.init(redis_connection)
    yield
    await FastAPILimiter.close()
